#coding=utf-8
import requests
import mysql_password_admin
# 导入requests_toolbelt库使用MultipartEncoder
from requests_toolbelt import MultipartEncoder
import random

def admin_login(mobile):
    # 通过mysql_password方法获取到该用户的salt加密后的密码
    password = mysql_password_admin.password(mobile)[0]
    userid = mysql_password_admin.password(mobile)[1]
    s = requests.session()
    check_mobile = s.get('http://community-bms-api-test.gdgyun.com/mgt/api/community/check/mobile?mobile='+str(mobile))  #判断手机号是否注册
    check_msg = check_mobile.json()["msg"]
    if check_msg == '该员工账号已注册':
        login_check = s.get('http://community-bms-api-test.gdgyun.com/mgt/api/community/doLogin?mobile='+str(mobile)+'&&password='+str(password))
        msg = '账号登录成功'
        login = s.get('http://community-bms-api-test.gdgyun.com/mgt/api/community/login?msg='+str(msg))  #进行登录
        token = str(login.json()["data"]["token"])
        # 定义headers
        headers = {'Accept': 'application/json, text/plain, */*', 'Accept-Encoding': 'gzip, deflate','Accept-Language': 'zh-CN,zh;q=0.9'
            ,'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'
            , 'Referer': 'http://community-bms-web-test.gdgyun.com/', 'Uid': str(userid), 'Authorization': token,'Origin': 'http://community-bms-web-test.gdgyun.com'
            , 'Host': 'community-bms-api-test.gdgyun.com', 'Content-Type': 'multipart/form-data'}
        return headers
    else:
        return u'该员工账号未注册'

#通过上传图片接口获得图片的url并返回
def uploadPhoto(filename):
    s = requests.session()
    headers = admin_login('17700010005')   #调用登录函数进行登录获取headers
    files = {"file":(filename,open("D:/images/code/"+filename,"rb"),"image/png",{})}
    # 生成可用于multipart/form-data上传的数据
    m = MultipartEncoder(files)
    # 自动生成Content-Type类型和随机码
    headers['Content-Type'] = m.content_type
    upload = s.post('http://community-fs-api-test.gdgyun.com/api/community/fs/upload/image',headers=headers,data=m)
    photoUrl = upload.json()["data"]["linkUrl"]
    print photoUrl
    return photoUrl


if __name__ =='__main__':
    randomNum = str(random.randint(1, 6))
    uploadPhoto(randomNum+".png")